package com.zhuhjay.service.system.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.common.base.config.SystemConfig;
import com.zhuhjay.common.base.exception.BasicBusinessException;
import com.zhuhjay.common.base.util.BeanBuilder;
import com.zhuhjay.common.security.context.LoginUserContext;
import com.zhuhjay.common.web.model.vo.PageInfoVo;
import com.zhuhjay.common.web.util.FileUtils;
import com.zhuhjay.service.system.mapper.SystemPictureMapper;
import com.zhuhjay.service.system.model.entity.SystemPicture;
import com.zhuhjay.service.system.model.vo.PictureVo;
import com.zhuhjay.service.system.service.SystemPictureService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

import static com.zhuhjay.common.base.constant.ApplicationConstant.PATH_SEPARATOR;
import static com.zhuhjay.common.base.constant.ApplicationConstant.PICTURE_BED_PATH;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Zhuhjay
 * @since 2023-05-10
 */
@Service
public class SystemPictureServiceImpl extends ServiceImpl<SystemPictureMapper, SystemPicture> implements SystemPictureService {

    @Resource
    private SystemConfig systemConfig;

    @Override
    public String upload(MultipartFile file, String origin) {
        FileUtils.checkFileIsImage(file);

        final String filePath = systemConfig.getPictureBedPath();
        File dir = FileUtil.mkdir(filePath);

        String fileName = FileUtils.generateFileName(file.getOriginalFilename());

        try {
            FileUtil.writeBytes(file.getBytes(), dir + PATH_SEPARATOR + fileName);
        } catch (IOException e) {
            throw new BasicBusinessException("图片上传失败");
        }

        SystemPicture picture = BeanBuilder.builder(SystemPicture::new)
                .with(SystemPicture::setRealName, file.getOriginalFilename())
                .with(SystemPicture::setFilePath, "/profile/" + PICTURE_BED_PATH + "/" + fileName)
                .with(SystemPicture::setSize, file.getSize())
                .with(SystemPicture::setOrigin, origin)
                .with(SystemPicture::setUserId, LoginUserContext.getUserId())
                .build();

        this.save(picture);
        return picture.getFilePath();
    }

    @Override
    public PageInfoVo<PictureVo> picturePage(Integer pageNum, Integer pageSize) {
        Page<SystemPicture> page = this.lambdaQuery()
                .eq(SystemPicture::getUserId, LoginUserContext.getUserId())
                .orderByDesc(SystemPicture::getCreateTime).page(Page.of(pageNum, pageSize));

        PageInfoVo<PictureVo> pageInfoVo = new PageInfoVo<>();
        pageInfoVo.setTotal(page.getTotal());
        pageInfoVo.setSize(page.getSize());
        pageInfoVo.setCurrent(page.getCurrent());
        pageInfoVo.setRecords(page.getRecords().stream()
                .map(picture -> PictureVo.of(picture, LoginUserContext.getUsername()))
                .collect(Collectors.toList()));
        return pageInfoVo;
    }

    @Override
    public void removePicture(Long id) {
        // 判断是否是当前用户的图片
        SystemPicture picture = this.lambdaQuery()
                .eq(SystemPicture::getId, id)
                .eq(SystemPicture::getUserId, LoginUserContext.getUserId())
                .one();
        if (picture == null) {
            throw new BasicBusinessException("删除失败, 该图片不存在");
        }
        this.removeById(id);
        // 删除本地文件
        final String resourceBasePath = systemConfig.getProfileLocation();
        FileUtil.del(picture.getFilePath().replace("/profile", resourceBasePath));
    }
}
